import React, { Component } from 'react'
import * as d3 from 'd3'

export default class Selection extends Component {
    
    _rebuild_svg(el){
        d3.select(el).selectAll('svg').remove()
        let svg = d3.select(el).insert("svg")
        return svg
    }
    
    // 绘制矩形并设置样式
    fun_attr_and_style() {
        let data = [5, 10, 15, 20, 25];
        let shape = d3.select(".fun_attr_and_style").selectAll()
            .data(data)
            .enter()
            .append('rect')
            .attr("x", function (d, i) { return 20 + i * 160 / data.length;})
            .attr("y", 20)
            .attr("width", 20)
            .attr("height", 100)
            .attr("fill", "blue")
        shape.style("stroke-width",5) //样式 1
        shape.style("stroke", function (d, i) { return "rgb(" + 10 * d + "," + 10 * (25 - d) + "," + d + ")"; }) //样式 2


    }

    // 测试插入和删除
    fun_insert_and_remove(){
        console.time("a")
        let svg = this._rebuild_svg('.insert_and_remove')
        svg.insert("rect").attr('x', 10).attr('y', 100).attr('width', 20).attr('height', 60).attr('fill', "forestgreen")
        // svg.insert("rect").attr('x', 40).attr('y', 100).attr('width', 20).attr('height', 60).attr('fill', "forestgreen")
        console.timeEnd("a")
    }

    fun_exit(){
        
        let data1 = [1,2,3,4,5,6]
        let data2 = [4,5,6,7,8,9]

        d3.select('.exit').selectAll('p').data(data1).append('p').text((d) => d)
        let ps = d3.select('.exit').selectAll('p').data(data2,(d)=>d)
        ps.enter().append('p').text((d) => d+2)
        ps.exit().remove()
        d3.select('.exit').selectAll('p').attr("index",(d)=>d)

    }


    componentDidMount() {
        this.fun_attr_and_style()
        this.fun_insert_and_remove()
        this.fun_exit()

    }

    render() {
        return (
            <div style={{'display':'flex'}}>
                <svg className="fun_attr_and_style"></svg>
                <div className="insert_and_remove" style={{height:'200px'}}></div>
                
            </div>
        )
    }
}
